package com.ztstkj.lzboard.ui

import android.annotation.SuppressLint
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.ViewGroup
import android.widget.MediaController
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.TimeUtils
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.Legend.LegendDirection
import com.github.mikephil.charting.components.Legend.LegendHorizontalAlignment
import com.github.mikephil.charting.components.Legend.LegendOrientation
import com.github.mikephil.charting.components.Legend.LegendVerticalAlignment
import com.github.mikephil.charting.components.XAxis.XAxisPosition
import com.github.mikephil.charting.components.YAxis.YAxisLabelPosition
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.charting.formatter.IValueFormatter
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.utils.ViewPortHandler
import com.sscl.baselibrary.utils.DebugUtil
import com.ztstkj.lzboard.R
import com.ztstkj.lzboard.adapters.NotCivAdapter
import com.ztstkj.lzboard.adapters.UserExchangeAdapter
import com.ztstkj.lzboard.adapters.UserRankAdapter
import com.ztstkj.lzboard.adapters.UserRealDeliveryAdapter
import com.ztstkj.lzboard.databinding.ActivityMainBinding
import com.ztstkj.lzboard.databinding.ExchangeBinding
import com.ztstkj.lzboard.databinding.HeaderBinding
import com.ztstkj.lzboard.databinding.NotCivBinding
import com.ztstkj.lzboard.databinding.RankBinding
import com.ztstkj.lzboard.databinding.RealDeliveryBinding
import com.ztstkj.lzboard.databinding.SevenDeliveryBinding
import com.ztstkj.lzboard.databinding.TodayDeliveryBinding
import com.ztstkj.lzboard.databinding.TodaySummaryBinding
import com.ztstkj.lzboard.databinding.VideoBinding
import com.ztstkj.lzservices.dto.HeartInput
import com.ztstkj.lzservices.dto.boards.BoardExchangeOutput
import com.ztstkj.lzservices.dto.boards.BoardInput
import com.ztstkj.lzservices.dto.boards.BoardRankOutput
import com.ztstkj.lzservices.dto.boards.BoardRealDeliveryOutput
import com.ztstkj.lzservices.dto.boards.BoardSevenDeliveryOutput
import com.ztstkj.lzservices.dto.boards.BoardTodaySummaryOutput
import com.ztstkj.lzservices.events.EventCard
import com.ztstkj.lzservices.events.EventJgPush
import com.ztstkj.lzservices.exceptions.LogConstant
import com.ztstkj.lzservices.exceptions.apiCall
import com.ztstkj.lzservices.extension.ExceptionExt.toStackTraceString
import com.ztstkj.lzservices.mmkvs.MmkvManager
import com.ztstkj.lzservices.networks.DowloadManager
import com.ztstkj.lzservices.networks.NetworkUtils
import com.ztstkj.lzservices.retrofits.Api
import com.ztstkj.lzservices.utils.LogcatUtil
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.net.URI
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import kotlin.math.min

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var headBidng: HeaderBinding
    private lateinit var todaySummaryBinding: TodaySummaryBinding
    private lateinit var rankBinding: RankBinding
    private lateinit var exchangeBinding: ExchangeBinding
    private lateinit var todayDeliveryBinding: TodayDeliveryBinding
    private lateinit var videoBinding: VideoBinding
    private lateinit var realDeliveryBinding: RealDeliveryBinding
    private lateinit var sevenDeliveryBinding: SevenDeliveryBinding
    private lateinit var notCivBinding: NotCivBinding
    private lateinit var timer: Timer
    private var videoStart: Boolean = false
    private lateinit var schedulerTenSec: ScheduledExecutorService
    private lateinit var schedulerFiveMin: ScheduledExecutorService
    private lateinit var schedulerNet: ScheduledExecutorService
    private lateinit var schedulerOne: ScheduledExecutorService
    private val tag:String=this.javaClass.simpleName
    private var isLogToFile: Boolean=false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        setBinding()
        EventBus.getDefault().register(this)
        initDevice()
        setTimes()
        //showScreenValue()
        initScheduledOne()
        initScheduledFivMin()
        //initScheduledTenSec()
        checkNet()
    }
    private fun initDevice(){
        headBidng.tvEquipmentNumber.text = buildString {
            append("设备号：")
            append(DeviceUtils.getAndroidID())
        }
        headBidng.tvBoardName.setOnClickListener {
            if(!isLogToFile){
                isLogToFile=true
                LogcatUtil.start(baseContext)
            }else{
                isLogToFile=false
                LogcatUtil.close(baseContext)
            }
        }
    }
    private fun checkNet() {
        schedulerNet = Executors.newScheduledThreadPool(1)
        schedulerNet.scheduleWithFixedDelay({
            DebugUtil.debugOut(tag,"60秒任务：网络检查:"+ NetworkUtils.onLine)
            NetworkUtils.onLine = NetworkUtils.isConnected(this)

        }, 1, 60, TimeUnit.SECONDS)
    }
    private fun initScheduledTenSec() {
        schedulerTenSec = Executors.newScheduledThreadPool(1)
        schedulerTenSec.scheduleWithFixedDelay({
            if (NetworkUtils.onLine) {
                DebugUtil.debugOut(tag,"15秒任务")
                getBoard()
            }
        }, 3, 15, TimeUnit.SECONDS)
    }
    private fun initScheduledFivMin() {
        schedulerFiveMin = Executors.newScheduledThreadPool(1)
        schedulerFiveMin.scheduleWithFixedDelay({
            if (NetworkUtils.onLine) {
                DebugUtil.debugOut(tag,"5分钟任务")
                taskHeart()
                getBoard()
            }
        }, 0, 5, TimeUnit.MINUTES)
    }
    private fun initScheduledOne() {
        schedulerOne = Executors.newScheduledThreadPool(1)
        schedulerOne.scheduleWithFixedDelay({
            if (NetworkUtils.onLine) {
                DebugUtil.debugOut(tag,"60秒任务")
                taskUploadLog()
            }

        }, 15, 60, TimeUnit.SECONDS)
    }
    private fun taskUploadLog() {
        val logs = MmkvManager.getTopLog()
        if (logs == null) {
            DebugUtil.debugOut(tag,"待上传日志：0，日志启用：${MmkvManager.enableLog}")
            return
        }
        lifecycleScope.launch {
            DebugUtil.debugOut(tag, GsonUtils.toJson(logs))
            val resp = apiCall { Api.get().postLog(logs) }
            if (resp.success) {
                MmkvManager.removeLog(logs.map { log -> log.createtime.toString() })
                taskUploadLog()
            }
        }
    }
    private fun taskHeart() {
        lifecycleScope.launch {
            val heartInput = HeartInput(DeviceUtils.getAndroidID(), AppUtils.getAppVersionName())
            heartInput.equipmentType="看板屏幕"
            val resp = apiCall { Api.get().postHeart(heartInput) }
            if (resp.success && resp.data != null) {

            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventJgPush(e: EventJgPush) {
        DebugUtil.debugOut(tag,"调用数据")
        getBoard()
    }
    private fun getBoard() {
        lifecycleScope.launch {
            val resp = apiCall { Api.get().postBoard(BoardInput( DeviceUtils.getAndroidID())) }
            if (resp.success&&resp.data!=null) {
                val board = resp.data
                val rank = board?.ranks
                if (rank != null) {
                    if (rank.size > 5) {
                        setRankData1(rank.take(5))
                        setRankData2(rank.subList(5, min(rank.size, 10)))
                    } else {
                        setRankData1(rank.take(min(rank.size, 5)))
                    }
                }
                if(board!=null){
                    setEquipment(board.equipmentName)
                    setTodaySummary(board.todaySummary)
                    setExchangeData(board.exchanges)
                    setRealDeliveryData(board.realDelivery)
                    setTodayDeliveryPieChart(board.todaySummary)
                    if (!videoStart) {
                        downVideoAndPlay(board.videoUrl)
                        videoStart = true
                    }
                    board.sevenDelivery?.categories =
                        listOf("可回收物", "有害垃圾", "其它垃圾", "易腐垃圾")
                    setSevenDeliveryBarChart(board.sevenDelivery)
                    setNotCivPagerRecycler(board.notCivs)
                }

            }
        }
    }

    private fun setBinding() {
        binding = ActivityMainBinding.inflate(layoutInflater)
        headBidng = HeaderBinding.bind(binding.main)
        todaySummaryBinding = TodaySummaryBinding.bind(binding.main)
        rankBinding = RankBinding.bind(binding.main)
        exchangeBinding = ExchangeBinding.bind(binding.main)
        todayDeliveryBinding = TodayDeliveryBinding.bind(binding.main)
        videoBinding = VideoBinding.bind(binding.main)
        realDeliveryBinding = RealDeliveryBinding.bind(binding.main)
        sevenDeliveryBinding = SevenDeliveryBinding.bind(binding.main)
        notCivBinding = NotCivBinding.bind(binding.main)
        setContentView(binding.root)
    }

    private fun setEquipment(equipmentName: String? = null) {
        if (equipmentName != null) {
            headBidng.tvEquipmentName.text = equipmentName
        }
    }

    @SuppressLint("SetTextI18n")
    fun setTodaySummary(todaySummary: BoardTodaySummaryOutput?) {
        if (todaySummary == null) return
        val bind = todaySummaryBinding
        bind.todaySummaryPeopleValue.text = "${todaySummary.totalHouseholds}户"
        bind.todaySummaryWeightValue.text = "${todaySummary.totalWeight}Kg"
        bind.todaySummaryCountValue.text = "${todaySummary.goodDeliveryCount}次"
        bind.todaySummaryPerishableValue.text = "${todaySummary.perishableWeight}Kg"
        bind.todaySummaryOtherValue.text = "${todaySummary.otherWeight}Kg"
        bind.todaySummaryRecyclableValue.text = "${todaySummary.recyclableWeight}Kg"
        bind.todaySummaryParticipateValue.text = todaySummary.participationRate
        bind.todaySummaryAccuracyValue.text = todaySummary.passRate
    }

    @SuppressLint("SetTextI18n")
    fun showScreenValue() {
        headBidng.tvEquipmentNumber.setOnClickListener {
            if (binding.linearLayoutScreen.isVisible) {
                binding.linearLayoutScreen.visibility = ViewGroup.GONE
            } else if (binding.linearLayoutScreen.isGone) {
                binding.linearLayoutScreen.visibility = ViewGroup.VISIBLE
            }
        }
        val screen =
            "${ScreenUtils.getScreenWidth()}*${ScreenUtils.getScreenHeight()},dpi=${ScreenUtils.getScreenDensityDpi()},density=${ScreenUtils.getScreenDensity()}"
        binding.tvScreenInfo.text = screen
        binding.tvDatasetTextSize.text =
            "getDimension:${resources.getDimension(R.dimen.bar_dataset_text_size)},getDimensionDensity:${
                getDimensionDensity(
                    R.dimen.bar_dataset_text_size
                )
            }"
        binding.tvPieLegendTextSize.text =
            "getDimension:${resources.getDimension(R.dimen.pie_legend_text_size)},getDimensionDensity:${
                getDimensionDensity(
                    R.dimen.pie_legend_text_size
                )
            }"
        binding.tvPieHoleTextSize.text =
            "getDimension:${resources.getDimension(R.dimen.pie_hole_text_size)},getDimensionDensity:${
                getDimensionDensity(
                    R.dimen.pie_hole_text_size
                )
            }"
        binding.tvBarLegendTextSize.text =
            "getDimension:${resources.getDimension(R.dimen.bar_legend_text_size)},getDimensionDensity:${
                getDimensionDensity(
                    R.dimen.bar_legend_text_size
                )
            }"

    }

    private fun setTimes() {
        timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    headBidng.tvTime.text = TimeUtils.millis2String(
                        System.currentTimeMillis(),
                        "yyyy年MM月dd日 HH:mm:ss"
                    )
                }
            }

        }, 0, 1000)
    }
    fun setRankData1(ranks: List<BoardRankOutput>) {
        //设置布局排列方式，默认垂直排列
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        val recyclerview = rankBinding.rankRecycler1
        recyclerview.layoutManager = linearLayoutManager
        recyclerview.adapter = UserRankAdapter(ranks)
    }

    fun setRankData2(ranks: List<BoardRankOutput>) {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        val recyclerview = rankBinding.rankRecycler2
        recyclerview.layoutManager = linearLayoutManager
        recyclerview.adapter = UserRankAdapter(ranks)
    }
    fun setExchangeData(boardExchanges: List<BoardExchangeOutput>?) {
        if (boardExchanges == null) return
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        val recyclerview = exchangeBinding.exchangeRecycler
        recyclerview.layoutManager = linearLayoutManager
        recyclerview.adapter = UserExchangeAdapter(boardExchanges)
    }

    fun setRealDeliveryData(boardRealDelivery: List<BoardRealDeliveryOutput>?) {
        if (boardRealDelivery == null) return
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        val recyclerview = realDeliveryBinding.realDeliveryRecycler
        recyclerview.layoutManager = linearLayoutManager
        recyclerview.adapter = UserRealDeliveryAdapter(boardRealDelivery)
    }

    private fun playVideo(uri: Uri) {
        runOnUiThread {
            val videoView = videoBinding.video
            videoView.setVideoURI(uri)
            videoView.start()
            videoView.setOnCompletionListener {
                videoView.setVideoURI(uri)
                videoView.start()
            }
            val mediaController = MediaController(this)
            videoView.setMediaController(mediaController)
            mediaController.setMediaPlayer(videoView)
        }
    }

    fun setTodayDeliveryPieChart(boardTodaySummary: BoardTodaySummaryOutput?) {
        if (boardTodaySummary == null) return
        var size = 0f
        size = getDimensionDensity(R.dimen.pie_legend_text_size)
        val pieChart = todayDeliveryBinding.chartPieTodayDelivery
        val pieData = arrayListOf<PieEntry>()
        //条目名
        val label = arrayOf("可回收物", "其他垃圾", "易腐垃圾") // , "有害垃圾"
        val colors = arrayListOf(
            //用于设置各条目的颜色
            getColor(R.color.pie_recyclable_color),
            //getColor(R.color.pie_harmful_color),
            getColor(R.color.pie_perishable_color),
            getColor(R.color.pie_other_color),
        )
        pieData.add(PieEntry(boardTodaySummary.recyclableWeight.toFloat(), label[0]))
        //pieData.add(PieEntry(0f, label[1]))
        pieData.add(PieEntry(boardTodaySummary.otherWeight.toFloat(), label[1]))
        pieData.add(PieEntry(boardTodaySummary.perishableWeight.toFloat(), label[2]))

        val pieDataSet = PieDataSet(pieData, "")
        pieDataSet.colors = colors
        pieDataSet.setDrawValues(true) //是否绘制在饼图上的文字，bool类型
        //pieDataSet.setDrawIcons(false)
        pieDataSet.sliceSpace = 5f //设置饼图之间的距离
        pieDataSet.selectionShift = 10f //设置选中某个扇区之后的距离

        // 禁用显示每个扇区的百分比
        pieChart.setUsePercentValues(true) // 不使用百分比
        //圆洞
        pieChart.isDrawHoleEnabled = true
        pieChart.holeRadius = getDimensionDensity(R.dimen.pie_hole_radius)
        pieChart.setHoleColor(Color.WHITE)

        //半透明圈
        pieChart.transparentCircleRadius = 70f
        pieChart.setTransparentCircleColor(Color.WHITE)//设置透明圈的颜色
        pieChart.setTransparentCircleAlpha(50)//透明度0-255
        //中心

        pieChart.centerText = "今日投递"
        pieChart.setCenterTextSize(getDimensionDensity(R.dimen.pie_hole_text_size))
        pieChart.setCenterTextColor(getColor(R.color.pie_center_color))

        //设置标签
        pieChart.setDrawEntryLabels(true)
        //pieChart.setEntryLabelTypeface(Typeface.DEFAULT_BOLD)
        pieChart.setEntryLabelTextSize(size)
        pieChart.setEntryLabelColor(getColor(R.color.pie_label_color))
        //pieChart.setEntryLabelTypeface();//自定义标签

        //设置数据
        pieChart.setExtraOffsets(0f, 10f, 80f, 10f)
        pieDataSet.valueTextSize = size//数据文字大小
        pieDataSet.valueLineWidth = 3f //数据连接线宽度
        //pieDataSet.valueLinePart1Length=1f;
        // pieDataSet.valueTypeface = Typeface.DEFAULT_BOLD
        pieDataSet.valueLinePart1OffsetPercentage = 80f
        pieDataSet.valueLinePart1Length = 0.5f
        pieDataSet.valueTextColor = getColor(R.color.pie_value_color)
        pieDataSet.valueLineColor = Color.WHITE
        pieDataSet.xValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE // 标签在外显示
        pieDataSet.yValuePosition = PieDataSet.ValuePosition.OUTSIDE_SLICE // 百分比值在外显示
        pieDataSet.valueFormatter =
            IValueFormatter { value, entry, dataSetIndex, viewPortHandler -> //Log.e("pie chart", "indd=$value")
                "${value.toInt()}%"
            }
        pieDataSet.setDrawValues(true) //在扇区绘制x值

        //对于右下角一串字母的操作
        pieChart.description.isEnabled = false
        //是否显示右下角描述
        pieChart.description.text = "竹桐生态科技" //修改右下角字母的显示
        //pieChart.description.textSize = 20f //字体大小
        //pieChart.description.textColor = Color.RED //字体颜色

        //-----------------图例
        pieChart.legend.isEnabled = true // 图例
        pieChart.legend.setDrawInside(true)

        pieChart.legend.textSize = size
        pieChart.legend.formSize = size//设置图例的大小
        //pieChart.legend.typeface= Typeface.DEFAULT_BOLD
        pieChart.legend.orientation =
            LegendOrientation.VERTICAL //设置图例的排序方式，如水平排列和垂直排列，LegendOrientation枚举值
        //pieChart.legend.direction=LegendDirection.RIGHT_TO_LEFT //设置图例是在文字的左边还是右边
        pieChart.legend.verticalAlignment = LegendVerticalAlignment.TOP
        pieChart.legend.horizontalAlignment = LegendHorizontalAlignment.RIGHT
        //pieChart.setBackgroundColor(Color.BLUE); 背景

        pieChart.animateXY(2000, 2000) // 图3
        pieChart.run {
            data = PieData(pieDataSet)
        }
    }

    fun setSevenDeliveryBarChart(boardSevenDelivery: BoardSevenDeliveryOutput?) {
        if (boardSevenDelivery == null) return
        val barChart = sevenDeliveryBinding.barChartSevenDelivery
        setBarChartData(boardSevenDelivery)

        //----------------------------------------------------------------------
        barChart.extraTopOffset = 10f
        barChart.extraLeftOffset = 10f
        barChart.extraBottomOffset = 10f
        barChart.extraRightOffset = 10f
        val description = sevenDeliveryBinding.barChartSevenDelivery.description
        description.isEnabled = false
        //description.text=""
        //description.typeface
        //description.textColor =  //设置标题颜色
        //description.textSize =
        //description.textAlign=
        //description.xOffset=   //设置标题在X轴的偏移量
        //description.yOffset=     //设置标题在Y轴的偏移量
        //description.position=//同时设置x和y轴的偏移量
        val legend = sevenDeliveryBinding.barChartSevenDelivery.legend
        legend.isEnabled = true

        legend.textSize = getDimensionDensity(R.dimen.bar_legend_text_size)     //设置图例的文字大小
        legend.textColor = getColor(R.color.pie_label_color)        //设置图例文字的颜色
        //legend.typeface = Typeface.DEFAULT_BOLD //设置字体类型，如加粗
        //legend.orientation=LegendOrientation.HORIZONTAL       //设置图例的排序方式，如水平排列和垂直排列，LegendOrientation枚举值
        legend.horizontalAlignment =
            LegendHorizontalAlignment.CENTER //设置图例在水平方向上的对齐方式，LegendHorizontalAlignment枚举值
        legend.verticalAlignment =
            LegendVerticalAlignment.BOTTOM     // 设置图例在垂直方向上的对齐方式，LegendVerticalAlignment枚举值
        legend.direction = LegendDirection.LEFT_TO_RIGHT //设置图例是在文字的左边还是右边
        legend.form = Legend.LegendForm.SQUARE//设置图例形状，默认为方形，LegendForm枚举值;
        legend.formSize = getDimensionDensity(R.dimen.bar_legend_text_size) //设置图例的大小
        //legend.formLineWidth;//设置图例的长度，当图例为线条的时候才生效，其他不生效
        legend.formToTextSpace = 1f//设置图例距离文字的距离，float类型
        //legend.formLineDashEffect;
        legend.xOffset = 0f//设置图例在X方向上的偏移量
        legend.yOffset = 5f//设置图例在Y方向上的偏移量
        legend.setDrawInside(false)//是否将图例绘制在图形内部(注：在内部就看不见X轴方向的值了)
        //------------------------------------------
        //val labels = arrayOf("可回收物", "有害垃圾", "其它垃圾", "易腐垃圾")
        val labels = boardSevenDelivery.categories
        //val xAxisValues=arrayOf("周日","周一", "周二", "周三", "周四","周五","周六")
        val xAxisValues = boardSevenDelivery.weekNames
        val xAxis = sevenDeliveryBinding.barChartSevenDelivery.xAxis
        xAxis.isEnabled = true
        xAxis.textSize = getDimensionDensity(R.dimen.bar_legend_text_size)
        xAxis.textColor = getColor(R.color.pie_label_color)
        //xAxis.typeface = Typeface.DEFAULT_BOLD
        xAxis.setCenterAxisLabels(true) //   是否将x轴上的文字居中显示
        xAxis.axisLineColor = getColor(R.color.bar_line_color)  //设置靠近x轴第一条线的颜色
        xAxis.axisLineWidth = 2f //设置绘制靠近x轴的第一条线的宽度
        xAxis.position = XAxisPosition.BOTTOM         // 设置x轴显示在下方
        xAxis.setDrawLabels(true)  //是否绘制x轴上的标签
        xAxis.setDrawGridLines(true)   // 设置x轴不画线
        xAxis.gridColor = Color.WHITE
        xAxis.yOffset = 5f
        //xAxis.xOffset=
        //xAxis.setAxisMinValue(0f)     // 设置x轴标签从0开始
        //xAxis.setAxisMaxValue(labels.size.toFloat())  // 设置x轴显示的最大标签数量

        xAxis.axisMinimum = 0f//设置最小值
        xAxis.axisMaximum = 7f //设置最大值
        //xAxis.labelCount=8
        //xAxis.setCenterAxisLabels(true)  // x轴标签居中
        // 接下来这段代码尤其重要，网上几乎99%的资料说的都是错的，这里详解一下
        // 1、要想标签跟group中间对齐，必须保证：(barWidth + barSpace) * group + groupSpace = granularity
        // 2、granularity < 1，则右边会有空余；
        // 3、granularity = 1，则刚好在一个屏幕显示开；
        // 4、granularity > 1，则一个屏幕显示不开；
        val barSpace = 0.025f
        val groupSpace = 0.2f
        val barWidth = 0.18f//宽度
        val granularity = (barWidth + barSpace) * labels.size + groupSpace
        xAxis.granularity = granularity
        barChart.scaleX = granularity
        barChart.barData.barWidth = barWidth
        barChart.groupBars(0f, groupSpace, barSpace)//分组
//        xAxis.isGranularityEnabled=false
//        xAxis.granularity=1f
        xAxis.valueFormatter = object : IAxisValueFormatter {
            override fun getFormattedValue(
                value: Float,
                axis: AxisBase?
            ): String {
                //Log.e("X轴：", value.toString())
                if (value > -1 && value < xAxisValues.size) {
                    return xAxisValues[value.toInt()]
                }
                return ""
            }

            override fun getDecimalDigits(): Int {
                return 0
            }

        }
        //---------------------------------------------------------------
        barChart.axisRight.isEnabled = false
        val yAxis = barChart.axisLeft
        yAxis.isEnabled = true
        //yAxis.setDrawTopYLabelEntry(true) //是否绘制最上面的那个标签
        yAxis.setAxisMinimum(0f)
        val weightArray = ArrayList<Float>()
        weightArray.addAll(boardSevenDelivery.others)
        weightArray.addAll(boardSevenDelivery.harmfuls)
        weightArray.addAll(boardSevenDelivery.perishables)
        weightArray.addAll(boardSevenDelivery.recyclables)
        yAxis.setAxisMaximum((weightArray.max() * 1.5).toFloat())
        yAxis.setPosition(YAxisLabelPosition.OUTSIDE_CHART)   //设置标签是绘制在图形内部还是外部， YAxisLabelPosition枚举值
        yAxis.axisLineWidth = 2f //设置靠近y轴第一条线的宽度
        yAxis.axisLineColor = getColor(R.color.bar_line_color)       //设置靠近y轴第一条线的颜色
        yAxis.setDrawAxisLine(true)
        yAxis.gridColor = Color.WHITE//设置横向网格的颜色
        yAxis.gridLineWidth = 1f       //设置横向网格线的宽度
        yAxis.xOffset = 15f   //设置y轴在x方向上的偏移量
        yAxis.setTextSize(12f)        //设置y轴的字体大小
        yAxis.textColor = getColor(R.color.pie_label_color)        //设置y轴的字体颜色
        //yAxis.typeface = Typeface.DEFAULT_BOLD;         //设置y轴字体的类型，如加粗等
        //自定义样式
        yAxis.valueFormatter = object : IAxisValueFormatter {
            override fun getFormattedValue(
                value: Float,
                axis: AxisBase?
            ): String {
                return "${value.toInt()}"
            }

            override fun getDecimalDigits(): Int {
                return 0
            }
        }
        barChart.requestLayout()
        //updateCommonUI(barChart)
        //updateChartUI(barChart)
        //barChart.renderer=RoundedBarChartRendererAll(barChart, barChart.animator, barChart.viewPortHandler)
        //barChart.invalidate()

    }

    /**
     * 设置数据源
     */
    private fun setBarChartData(boardSevenDelivery: BoardSevenDeliveryOutput) {
        val colors: MutableList<Int> = ArrayList()
        colors.add(getColor(R.color.pie_recyclable_color))
        colors.add(getColor(R.color.pie_harmful_color))
        colors.add(getColor(R.color.pie_perishable_color))
        colors.add(getColor(R.color.pie_other_color))
        val barDataSets: MutableList<IBarDataSet> = ArrayList()

        for ((categryIndex, category) in boardSevenDelivery.categories.withIndex()) {
            val barEntries: MutableList<BarEntry> = ArrayList()
            var barDataSet = BarDataSet(barEntries, category)
            when (category) {
                "可回收物" -> {
                    for ((index, weight) in boardSevenDelivery.recyclables.withIndex()) {
                        barEntries.add(BarEntry((index + 1).toFloat(), weight))
                    }
                    barDataSet = BarDataSet(barEntries, category)
                }

                "有害垃圾" -> {
                    for ((index, weight) in boardSevenDelivery.harmfuls.withIndex()) {
                        barEntries.add(BarEntry((index + 1).toFloat(), weight))
                    }
                    barDataSet = BarDataSet(barEntries, category)
                }

                "其它垃圾" -> {
                    for ((index, weight) in boardSevenDelivery.others.withIndex()) {
                        barEntries.add(BarEntry((index + 1).toFloat(), weight))
                    }
                    barDataSet = BarDataSet(barEntries, category)
                }

                "易腐垃圾" -> {
                    for ((index, weight) in boardSevenDelivery.perishables.withIndex()) {
                        barEntries.add(BarEntry((index + 1).toFloat(), weight))
                    }
                    barDataSet = BarDataSet(barEntries, category)
                }
            }
            barDataSet.valueFormatter = object : IValueFormatter {
                override fun getFormattedValue(
                    value: Float,
                    entry: Entry?,
                    dataSetIndex: Int,
                    viewPortHandler: ViewPortHandler?
                ): String {
                    if (value > 0) return value.toString()
                    return ""
                }

            }
            barDataSet.color = colors[categryIndex]
            barDataSet.valueTextSize = getDimensionDensity(R.dimen.bar_dataset_text_size)
            barDataSet.valueTextColor = getColor(R.color.pie_value_color)
            //barDataSet.valueTypeface = Typeface.DEFAULT_BOLD
            barDataSet.form = Legend.LegendForm.SQUARE
            barDataSets.add(barDataSet)
        }
        val ba = BarData(barDataSets)
        sevenDeliveryBinding.barChartSevenDelivery.data = ba
    }

    private fun setNotCivPagerRecycler(images: List<String>?) {
        if (images == null) return
        val notCivAdapter = NotCivAdapter(this, images)
        notCivBinding.notCivViewPager.adapter = notCivAdapter
    }

    //    private  fun getNotCivBanner(){
//        var vp =notCivBinding.notCivViewPager
//        vp.pageMargin=80
//        vp.offscreenPageLimit=3
//        val images = arrayListOf<String>(
//            "https://ztstkj.oss-cn-hangzhou.aliyuncs.com/garbagePhoto/0001041c86e946ab8fb239c24ee77113.jpg",
//            "https://ztstkj.oss-cn-hangzhou.aliyuncs.com/garbagePhoto/00022c97ed1f4e6bb8d26e6e05ddc012.jpg",
//            "https://ztstkj.oss-cn-hangzhou.aliyuncs.com/garbagePhoto/00029be485464c04ba7c845762bf009e.jpg",
//            "https://ztstkj.oss-cn-hangzhou.aliyuncs.com/garbagePhoto/0000dcd31c6b44ac8240bcbd12a5b7cd.jpg",
//            "https://ztstkj.oss-cn-hangzhou.aliyuncs.com/garbagePhoto/0000ddde50e847dbab95147258fd15e2.jpg",
//            "https://ztstkj.oss-cn-hangzhou.aliyuncs.com/garbagePhoto/0000df290a2b406cb11226c22937913a.jpg"
//        )
//        val vpAdapter= NotCivAdapter(this@MainActivity,images)
//        vp.adapter=vpAdapter
//
//    }
//    private fun setNotCivBanner() {
//        var banner = (notCivBinding.notCivBanner as Banner<String, BannerImageAdapter<String>>)
//        var banner =notCivBinding.notCivBanner
//        banner.apply {
//            addBannerLifecycleObserver(this@MainActivity)
//            indicator = CircleIndicator(this@MainActivity)
//            setAdapter(object : BannerImageAdapter<String>(images) {
//                override fun onBindView(holder: BannerImageHolder, data: String, position: Int, size: Int) {
//                    Glide.with(this@MainActivity.applicationContext)
//                        .load(data)
//                        .into(holder.imageView)
//                }
//            })
//        }
//    }

    private fun getFileNameFromUrl(urlString: String): String {
        val uri = URI(urlString)
        val path = uri.path
        val fileName = path.substringAfterLast('/')
        return fileName
    }

    private fun getDimensionDensity(id: Int): Float {
        return resources.getDimension(id) / ScreenUtils.getScreenDensity()
    }

    private fun downVideoAndPlay(url: String?) {
        if (url == null) return
        val fileName = getFileNameFromUrl(url)
        val downloadedFile = File(this.cacheDir, fileName)
        if (downloadedFile.exists()) {
            DebugUtil.warnOut(tag,"文件已存在！$fileName," + downloadedFile.path)
            playVideo(Uri.fromFile(downloadedFile))
        } else {
            lifecycleScope.launch {
                var processNum = 0
                DowloadManager.download(url, downloadedFile.path, onProcess = { _, _, process ->
                    val processInt = (process * 100).toInt()
                    if (processInt % 10 == 0 && processNum != processInt) {
                        processNum = processInt
                        MmkvManager.addLog(LogConstant.APPDOWN, "process =$processInt%")
                    }
                }, onSuccess = {
                    MmkvManager.addLog(
                        LogConstant.APPDOWN,
                        "下载成功,地址：${downloadedFile.path}"
                    )
                    playVideo(Uri.fromFile(downloadedFile))
                }, onError = {
                    it.printStackTrace()
                    MmkvManager.addLog(LogConstant.APPDOWN, "下载失败,${it.toStackTraceString()}")
                })
            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}